import os
import json
import sys

import resources
import logger
from save import Save

class Localizer:

    """
    向MC学习的本地化机制。
    """
    
    I = None
    def __init__(self) -> None:
        if not Localizer.I: Localizer.I = self

        # 如果没有lang_location, 就设置为: 程序目录下的 lang 文件夹
        main_dir = os.path.dirname(__file__)
        exe_dir = os.path.dirname(sys.executable)

        self.langLocation = os.path.realpath( os.path.join(main_dir,"./lang/") )
        
        self.exeLangLocation = os.path.realpath( os.path.join(exe_dir,"./lang/"))

        try:
            self.langResources = resources.Resource.create(self.langLocation)
        except FileNotFoundError:
            self.langResources = resources.Resource.create(self.exeLangLocation)

        self.currentLanguage = "en_us"
        self.localizeTable = None

    def loadLanguage(self, lang:str) -> None:
        # 减少不必要性能消耗
        if self.localizeTable and self.currentLanguage == lang: return

        # 找不到就警告
        r = self.langResources.get("{}.json".format(lang))
        if not r:
            logger.Logger.I.log("Language file <{}.json> not found!".format(lang))
            return

        #读取
        r.read()
        self.localizeTable = json.load(r.file)
        r.close()
        # 结束再设置
        self.currentLanguage = lang
    
    def get(self, localize_id:str) -> str:
        # 获取文本
        text = self.localizeTable.get(localize_id,None)
        # 如果没有获取到就直接设置为localize_id
        if not text: text = localize_id

        return text
    
    def toGlobal(self, save:Save) -> None:
        save.global_data["language"] = self.currentLanguage

    def fromGlobal(self, save:Save) -> None:
        self.currentLanguage = save.global_data["language"]
        self.loadLanguage(self.currentLanguage)
